<template>
  <div class="oneNet">
    <el-table :data="tableData">
      <el-table-column prop="serialNumber" label="序号" width="80">
        <template #default="scope">
          <div>
            {{ scope.$index + 1 }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="serverName" label="功能、数据名称" />
      <el-table-column prop="sentences" label="常用命令词">
        <template #default="scope">
          <div
            v-for="(item, sentenceIndex) in formatTableCommonSentence(
              scope.row.sentences
            )"
            :key="sentenceIndex"
          >
            {{ item }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="userTypes" label="所属角色">
        <template #default="scope">
          <div>
            {{ getRoleByUserTypes(scope.row.userTypes) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="schoolId" label="所属学校">
        <template #default="scope">
          <div>
            {{ props.schoolMap?.get(scope.row.schoolId) ?? "" }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="orderNo" label="高频服务排序">
        <template #default="scope">
          <div>
            {{ scope.row.trigger === "0" ? null : scope.row.orderShowNum }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            :type="scope.row.trigger === '0' ? 'primary' : ''"
            size="small"
            @click="triggerServer(scope.$index, scope.row)"
            >{{
              scope.row.trigger === "0" ? "加入高频" : "取消高频"
            }}</el-button
          >
          <el-button
            size="small"
            @click="editInstructs(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            v-show="scope.row.trigger === '1'"
            :disabled="!(scope.row.trigger === '1' && scope.$index != 0)"
            size="small"
            @click="handleServerUp(scope.$index, scope.row, true)"
            title="上移"
          >
            <el-icon><Top /></el-icon>
          </el-button>
          <el-button
            v-show="scope.row.trigger === '1'"
            :disabled="!isAbleToMoveDown(scope.$index)"
            size="small"
            @click="handleServerUp(scope.$index, scope.row, false)"
            title="下移"
          >
            <el-icon><Bottom /></el-icon>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { Bottom, Top } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { cloneDeep } from "lodash-es";
import { computed } from "vue";
import { oneNetUserType } from "../enum";
import { formatTableCommonSentence } from "../utils";

const props = defineProps({
  tableData: Array,
  schoolMap: Map,
  editInstructs: Function,
  triggerServer: Function,
  changeServerPosition: Function,
  refresh: Function,
});

const tableData = computed(() => {
  const arr = cloneDeep(props.tableData);

  arr?.sort((a, b) => {
    if (a.trigger == "0" && b.trigger == "0") {
      return -1;
    } else if (a.trigger == "1" && b.trigger == "0") {
      return -1;
    } else if (b.trigger == "1" && a.trigger == "0") {
      return 1;
    }

    return a.orderNo - b.orderNo;
  });

  const len = arr?.length;
  for (let i = 0; i < len; i++) {
    const item = arr?.[i];
    if (item?.trigger == "0") {
      break;
    }
    item.orderShowNum = i + 1;
  }

  return arr || [];
});

const editInstructs = (index, row) => {
  props.editInstructs?.(index, row);
};

// 取消/加入高频
const triggerServer = async (index, row) => {
  row.trigger = row.trigger == "1" ? "0" : "1";
  row.userType = row.userTypes;

  let result = await props.triggerServer?.(row);

  if (result && result.success) {
    ElMessage.success("操作成功");
    props.refresh?.();
  } else {
    row.trigger = row.trigger == "1" ? "0" : "1";
    ElMessage.error("网络异常");
  }
};

// 服务上移
const handleServerUp = async (index, row, isUp) => {
  // 获取上一个服务的orderNo
  let preServer = null;
  if (isUp) {
    preServer = tableData?.value?.[index - 1];
  } else {
    preServer = tableData?.value?.[index + 1];
  }

  const curOrderNo = row.orderNo;
  const preOrderNo = preServer?.orderNo;

  row.orderNo = preOrderNo;
  preServer.orderNo = curOrderNo;

  const result1 = await props.changeServerPosition?.(row);

  if (!(result1 && result1.success)) {
    ElMessage.error("网络异常");
    return;
  }

  const result2 = await props.changeServerPosition?.(preServer);

  if (result2 && result2.success) {
    ElMessage.success("操作成功");
    props.refresh?.();
  } else {
    ElMessage.error("网络异常");
  }
};

const getRoleByUserTypes = (userTypes: string) => {
  let arr = userTypes.split(",");

  let str = "";
  arr.forEach((userType) => {
    if (["0", "1", "2"].includes(userType)) {
      str += oneNetUserType[userType] + "、";
    }
  });
  if (!str) {
    return "无角色";
  }
  return str.slice(0, -1);
};

// 是否能下移
const isAbleToMoveDown = (index) => {
  if (index + 1 >= tableData.value?.length) {
    return false;
  }

  if (tableData?.value?.[index + 1]?.trigger == "0") {
    return false;
  }

  return true;
};

const sortOrderNo = (a, b) => {
  if (a.trigger == "1" && b.trigger == "1") {
    return b.orderShowNum - a.orderShowNum;
  } else if (a.trigger == "1") {
    return -1;
  } else if (b.trigger == "1") {
    return -1;
  }

  return -1;
};
</script>

<style lang="scss" scoped>
.oneNet {
  height: 100%;
  :deep(.el-table) {
    height: 100%;
  }
}

table {
  th:nth-child(3),
  td:nth-child(3) {
    overflow-y: scroll;
    max-height: 200px;
  }
}
</style>
